import os
from openai import OpenAI
from .base_llm import BaseLLM

class OpenAIChat(BaseLLM):
    def __init__(self):
        super().__init__("OpenAI")
        self.base_url = os.getenv("OPENAI_BASE_URL", "https://apimgateway.siemens-healthineers.com/openai")
        self.api_version = os.getenv("OPENAI_API_VERSION", "2025-03-01-preview")
        
        self.client = OpenAI(
            api_key=os.getenv("OPENAI_API_KEY"),
            base_url=f"{self.base_url}/deployments/gpt-4o",
            default_headers={
                "api-key": os.getenv("OPENAI_API_KEY")
            }
        )

    def converse_stream(self, history):
        # 转换历史记录格式（兼容 AWS 的 [{"text": content}] 结构）
        messages = []
        for msg in history:
            if msg["role"] not in ("user", "assistant"):
                continue
            
            # 提取消息内容
            content = msg.get("content", "")
            if isinstance(content, list) and len(content) > 0:
                text = content[0].get("text", "").strip() or " "  # 兼容 AWS 格式
            else:
                text = str(content).strip() or " "  # 直接处理字符串内容
            
            messages.append({
                "role": msg["role"],
                "content": text
            })

        try:
            # 调用 OpenAI 流式 API
            stream = self.client.chat.completions.create(
                model="chat",  # 固定模型名称
                messages=messages,
                stream=True,
                max_tokens=4096,
                temperature=0.5,
                top_p=0.9,
                extra_query={
                    "api-version": self.api_version
                }
            )

            # 流式返回响应
            for chunk in stream:
                if content := chunk.choices[0].delta.content:
                    yield content

        except Exception as e:
            yield f"ERROR: {str(e)}"

    def _perform_connection_check(self):
        try:
            test = self.client.chat.completions.create(
                model="chat",
                messages=[{"role":"user","content":"ping"}],
                max_tokens=5
            )
            return {"status": True}
        except Exception as e:
            return {"status": False, "detail": str(e)}